package com.cloudwave.trailends.ui;

import java.util.ArrayList;
import java.util.List;

import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ExpandableListView;
import android.widget.GridView;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.TextView;

import com.baidu.mapapi.SDKInitializer;
import com.baidu.mapapi.map.offline.MKOLSearchRecord;
import com.baidu.mapapi.map.offline.MKOLUpdateElement;
import com.baidu.mapapi.map.offline.MKOfflineMap;
import com.baidu.mapapi.map.offline.MKOfflineMapListener;
import com.cloudwave.trailends.R;
import com.cloudwave.trailends.adapter.AllCityAdapter;
import com.cloudwave.trailends.adapter.HotCityAdapter;
import com.cloudwave.trailends.adapter.OfflineMapAdapter;
import com.cloudwave.trailends.compo.BaseActivity;
import com.cloudwave.trailends.utils.CollectionUtils;

public class OfflineMapActivity extends BaseActivity implements MKOfflineMapListener {
	private static final String TAG = "OfflineMapActivity";
	
	private ImageButton btnBack;
	private TextView tvTitle;
	private ImageButton btnOK;
	
	private MKOfflineMap mOffline = null;
	
	private List<MKOLUpdateElement> offlineList = null;
	private ListView offlineCityList; 
	private OfflineMapAdapter offlineMapAdapter;
	
	private GridView gvHotCityGrid;
	private HotCityAdapter hotCityAdapter;
	
	private AllCityAdapter allCityAdapter;
	private ExpandableListView allCityList;
	
	private View llAllCity;
	private View llOffline;
	private int offlinePage = 1;
	
	private int curCityId = 0;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		 SDKInitializer.initialize(getApplicationContext());
		setContentView(R.layout.offline_map);
		
		initView();
		
		mOffline = new MKOfflineMap();
		mOffline.init(this);
		
		initOfflineListView();
		
		initGridView();
		
		initListView();
		
		if ( CollectionUtils.isEmpty(offlineList) ) {
			llOffline.setVisibility(View.GONE);
			llAllCity.setVisibility(View.VISIBLE);
			btnOK.setImageResource(R.drawable.offline_map_btn);
			offlinePage = 2;
		} else {
			btnOK.setImageResource(R.drawable.offline_city_list);
		}
	}
	
	private void initView() {
		btnBack = (ImageButton) findViewById(R.id.btnBack);
		tvTitle = (TextView) findViewById(R.id.tvTitle);
		btnOK = (ImageButton) findViewById(R.id.btnOK);
		
		llOffline = (View) findViewById(R.id.llOffline);
		offlineCityList = (ListView) findViewById(R.id.lvOfflineMap);
		
		llAllCity = findViewById(R.id.llAllCity);
		gvHotCityGrid = (GridView) findViewById(R.id.gvHotCityGrid);
		allCityList = (ExpandableListView) findViewById(R.id.lvAllCityList);
		
		
		tvTitle.setText("离线地图");
		btnOK.setVisibility(View.VISIBLE);
		
		btnBack.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				OfflineMapActivity.this.finish();
			}
			
		});
		
		btnOK.setOnClickListener(new View.OnClickListener() {
			
			@Override
			public void onClick(View v) {
				if ( offlinePage == 1 ) {
					llOffline.setVisibility(View.GONE);
					llAllCity.setVisibility(View.VISIBLE);
					btnOK.setImageResource(R.drawable.offline_map_btn);
					offlinePage = 2;
				} else {
					llOffline.setVisibility(View.VISIBLE);
					llAllCity.setVisibility(View.GONE);
					btnOK.setImageResource(R.drawable.offline_city_list);
					offlinePage = 1;
				}
			}
			
		});
	}
	
	private void initOfflineListView() {
		offlineList = mOffline.getAllUpdateInfo();
		if (offlineList == null) {
			offlineList = new ArrayList<MKOLUpdateElement>();
		}
		offlineMapAdapter = new OfflineMapAdapter(this, offlineList);
		offlineCityList.setAdapter(offlineMapAdapter);
	}
	
	private void initGridView() {
		// 获取热门城市列表
		final List<MKOLSearchRecord> records = mOffline.getHotCityList();
		// ###热门城市考虑移除掉香港和澳门
//		List<MKOLSearchRecord> recordList = new ArrayList<MKOLSearchRecord>();
//		for ( MKOLSearchRecord r : records ) {
//			if ( r.cityName.contains("香港") || r.cityName.contains("澳门") ) {
//				continue ;
//			} else {
//				recordList.add(r);
//			}
//		}
		hotCityAdapter = new HotCityAdapter(this, records);
		gvHotCityGrid.setAdapter(hotCityAdapter);
		allCityList.setGroupIndicator(null);
		
		gvHotCityGrid.setOnItemClickListener(new OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view,
					int position, long id) {
				MKOLSearchRecord record = records.get(position);
				start(record.cityID);
				btnOK.setImageResource(R.drawable.offline_downloading_btn);  //###貌似不起作用
			}
		});
	}
	
	private void initListView() {
		//获取所有城市列表
		final List<MKOLSearchRecord> records = mOffline.getOfflineCityList();
		allCityAdapter = new AllCityAdapter(this, records);
		allCityList.setAdapter(allCityAdapter);
		allCityList.setGroupIndicator(null);
//		allCityList.setGroupIndicator(this.getResources().getDrawable(R.drawable.ext_group_list_flag));
	
//		expandGroup (int groupPos) ;//在分组列表视图中 展开一组，
//		setSelectedGroup (int groupPosition) ;//设置选择指定的组。
//		setSelectedChild (int groupPosition, int childPosition, boolean shouldExpandGroup);//设置选择指定的子项。
//		getPackedPositionGroup (long packedPosition);//返回所选择的组
//		getPackedPositionForChild (int groupPosition, int childPosition) ;//返回所选择的子项
//		getPackedPositionType (long packedPosition);//返回所选择项的类型（Child,Group）
//		isGroupExpanded (int groupPosition);//判断此组是否展开
		
		allCityList.setOnGroupClickListener(new ExpandableListView.OnGroupClickListener() {

			@Override
			public boolean onGroupClick(ExpandableListView parent, View v,
					int groupPosition, long id) {
				MKOLSearchRecord record = records.get(groupPosition);
				if ( CollectionUtils.isEmpty(record.childCities) ) {
					start(record.cityID);
					btnOK.setImageResource(R.drawable.offline_downloading_btn);  //###貌似不起作用
					//###这里没起作用
//					TextView tvCityName = (TextView) v.findViewById(R.id.tvCityName);
//					String cityName = tvCityName.getText().toString();
//					tvCityName.setText(cityName+"(正在下载)");
				}
				return false;
			}
			
		});
		
		allCityList.setOnChildClickListener(new ExpandableListView.OnChildClickListener() {
			
			@Override
			public boolean onChildClick(ExpandableListView parent, View v,
					int groupPosition, int childPosition, long id) {
				MKOLSearchRecord record = records.get(groupPosition).childCities.get(childPosition);
				start(record.cityID);
				btnOK.setImageResource(R.drawable.offline_downloading_btn);  //###貌似不起作用
				return false;
			}
		});
	}
	
	public void start(int cityId) {
		mOffline.start(cityId);
		curCityId = cityId;
		updateDownload();
	}
	
	public void stop(int cityId) {
		mOffline.pause(cityId);
		curCityId = 0;
		updateDownload();
	}
	
	public void remove(int cityId) {
		mOffline.remove(cityId);
		updateDownload();
	}
	
	public void updateDownload() {
		if (offlineList == null) {
			offlineList = new ArrayList<MKOLUpdateElement>();
		} else {
			offlineList.clear();
			List<MKOLUpdateElement> offlineListTmp = mOffline.getAllUpdateInfo();
			if ( CollectionUtils.isNotEmpty(offlineListTmp) ) {
				offlineList.addAll(offlineListTmp);
			}
		}
		offlineMapAdapter.notifyDataSetChanged();
	}
	
	/**
	 * 从SD卡导入离线地图安装包
	 * @param view
	 */
//	public void importFromSDCard(View view) {
//		int num = mOffline.importOfflineData();
//		String msg = "";
//		if (num == 0) {
//			msg = "没有导入离线包，这可能是离线包放置位置不正确，或离线包已经导入过";
//		} else {
//			msg = String.format("成功导入 %d 个离线包，可以在下载管理查看", num);
//		}
//		Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();
//	}
	
	@Override
	public void onGetOfflineMapState(int type, int state) {
		switch (type) {
		case MKOfflineMap.TYPE_DOWNLOAD_UPDATE: {
			MKOLUpdateElement update = mOffline.getUpdateInfo(state);
				// 处理下载进度更新提示
				if ( update != null ) {
//					stateView.setText(String.format("%s : %d%%", update.cityName, update.ratio));
					updateDownload();
				}
			}
			break;
		case MKOfflineMap.TYPE_NEW_OFFLINE:
			// 有新离线地图安装
			Log.d(TAG, String.format("add offlinemap num:%d", state));
			break;
		case MKOfflineMap.TYPE_VER_UPDATE:
			// 版本更新提示
			// MKOLUpdateElement e = mOffline.getUpdateInfo(state);

			break;
		}
	}
	
	@Override
	protected void onPause() {
		mOffline.pause(curCityId);
		super.onPause();
	}
	
	@Override
	protected void onDestroy() {
		// 退出时，销毁离线地图模块
		mOffline.destroy();
		super.onDestroy();
	}
}

